package yang.itcode.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import yang.itcode.exception.BusinessException;
import yang.itcode.service.FileService;
import yang.itcode.service.SystemSettingService;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import static yang.itcode.constant.ErrorConstant.*;
import static yang.itcode.constant.FileConstant.FILE_EXTENSIONS;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private SystemSettingService systemSettingService;

    @Override
    public String uploadImage(MultipartFile file) {
        // 验证文件
        validateFile(file);

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new BusinessException(FILE_UPLOAD_EXCEPTION_CODE, "文件名不能为空");
        }
        String extension = getFileExtension(originalFilename);
        String newFilename = generateFilename() + extension;

        // 获取图片存储路径
        String imageAddress = systemSettingService.getSystemSetting().getStr("imageAddress");
        if (!imageAddress.endsWith("/")) {
            imageAddress += "/";
        }

        // 将文件保存到指定路径（这里假设是本地文件系统）
        try {
            String address = imageAddress + newFilename;
            file.transferTo(new java.io.File(address));
            return address;
        } catch (Exception e) {
            throw new BusinessException(FILE_UPLOAD_EXCEPTION_CODE, FILE_UPLOAD_EXCEPTION_MESSAGE);
        }
    }

    @Override
    public Resource getImage(String imagePath) {
        try {
            // 构建文件路径
            Path filePath = Paths.get(imagePath).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists() && resource.isReadable()) {
                return resource;
            } else {
                throw new BusinessException(FILE_NOT_FOUND_EXCEPTION_CODE, FILE_NOT_FOUND_EXCEPTION_MESSAGE);
            }
        } catch (MalformedURLException ex) {
            throw new BusinessException(FILE_PATH_EXCEPTION_CODE, FILE_PATH_EXCEPTION_MESSAGE);
        }
    }

    @Override
    public String determineContentType(String filename) {
        if (filename == null || !filename.contains(".")) {
            return "image/jpeg"; // 默认类型
        }
        String extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "webp":
                return "image/webp";
            case "bmp":
                return "image/bmp";
            default:
                return "image/jpeg"; // 默认类型
        }
    }

    private static void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new RuntimeException("文件名不能为空");
        }

        String extension = getFileExtension(filename).toLowerCase();
        boolean isAllowed = false;
        for (String allowedExt : FILE_EXTENSIONS) {
            if (allowedExt.equals(extension)) {
                isAllowed = true;
                break;
            }
        }

        if (!isAllowed) {
            throw new BusinessException(FILE_TYPE_EXCEPTION_CODE, FILE_TYPE_EXCEPTION_MESSAGE);
        }
    }

    private static String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        return lastDotIndex > 0 ? filename.substring(lastDotIndex) : "";
    }

    private static String generateFilename() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
